import { useEffect, useState } from 'react';
import { View } from '@tarojs/components';
import { Dialog, Input } from '@nutui/nutui-react-taro';
import { domain, domain2 } from '@/constant';
import { fetchUser, getUser } from '@/utils/user';
import Taro, { useDidShow } from '@tarojs/taro';
import CardUserAvatar from './components/card-user-avatar';
import CardSwiper from './components/card-swiper';
import CardActivity from './components/card-activity';
import CardBusiness from './components/card-business';
import CardComingSoon from './components/card-coming-soon';

import './index.less';
import { useDispatch, useSelector } from 'react-redux';
import { setAddress } from '@/store/address';
import { RootState } from '@/store';
import request from '@/utils/request';

export default function Index() {
  const [user, setUser] = useState(getUser());
  const [showDialog, setShowDialog] = useState(false);
  const dispatch = useDispatch();
  const addressState = useSelector((state: RootState) => state.address);
  // 编辑状态的临时数据
  const [community, setCommunity] = useState(addressState.community);
  const [building, setBuilding] = useState(addressState.building);
  const [unit, setUnit] = useState(addressState.unit);
  const [room, setRoom] = useState(addressState.room);



  useEffect(() => {
    if (user?.id) fetchUser(user.id).then((res) => {
      setUser(res);
      dispatch(setAddress({
        community: user.community,
        building: user.building,
        unit: user.unit,
        room: user.room,
      }));

      // 获取是否已经展示过地址弹窗
      const hasShownAddressDialog = Taro.getStorageSync('hasShownAddressDialog');
      
      // 只有在未展示过且没有填写地址信息时才显示弹窗
      if(!hasShownAddressDialog && !user.community && !user.building && !user.unit && !user.room){
        setShowDialog(true);
        // 标记已经展示过弹窗
        Taro.setStorageSync('hasShownAddressDialog', true);
      }
    });
  }, []);

  useDidShow(() => {
    const _user = getUser();
    if (_user?.id) fetchUser(_user.id).then((res) => {
      setUser(res);
      dispatch(setAddress({
        community: user.community,
        building: user.building,
        unit: user.unit,
        room: user.room,
      }));
    });
  });

  // const handleOpenLocation = () => {
  //   Taro.openLocation({
  //     latitude: 30.73234,
  //     longitude: 120.043363,
  //     name: 'VISO AI趣农场',
  //     address: '湖州市吴兴区东林镇钓妙线望乡岭西911米',
  //     scale: 18,
  //   });
  // };

  const handleSave = () => {
    if (!community || !building || !room) {
      Taro.showToast({
        title: '请填写小区名称、楼栋号和门牌号',
        icon: 'none',
      });
      return;
    }
    console.log("community",community);
    const saveAddress = async () => {
      // 调用接口保存地址
      const res = await request.post('/user/save-address', {
        userId: user.id,
        community,
        building,
        unit,
        room,
      });
      console.log("res",res);
      if (res) {
        Taro.showToast({
          title: '保存成功',
          icon: 'success',
        });
        // 保存到 store
        dispatch(setAddress({
          community,
          building,
          unit,
          room,
        }));
        // 关闭弹窗
        setShowDialog(false)
      }
    }
    saveAddress();

    
  };

  return (
    <View className="home">
      <CardSwiper />
      <CardUserAvatar user={user} />
      <CardBusiness user={user} />
      <CardComingSoon />
      {/* <CardActivity user={user} />
      <View className="footer">
        <Image className="login-title" src={`${domain2}/images/logoviso.png`} />
        <View className="address" onClick={handleOpenLocation}>
          <Location size={13} />
          &nbsp;湖州市吴兴区东林镇钓妙线望乡岭西911米
        </View>
        <View className="address-tip" onClick={handleOpenLocation}>
          （点击地址即可导航）
        </View>
        <View className="phone" onClick={handleMakePhoneCall}>
          <Phone size={13} /> &nbsp;1373633011
        </View>
        <View className="phone" onClick={handleMakePhoneCall}>
          <Mail size={13} /> &nbsp;jgn0206
        </View>
      </View> */}
      <View className="empty"></View>
      {/* <View 
      className="login-dialog"
      onClick={() => setShowDialog(true)}
      >111212112111</View> */}
      <Dialog
        visible={showDialog}
        // onClose={() => {
        //   console.log("onClose");
        //   setShowDialog(false)
        // }}
        onCancel={()=>{
          setShowDialog(false)
        }}
        title="提示"
        content={
          <View>
            <View className="home-dialog-content">
              <View className="form-item">
                <View className="label">小区名称</View>
                <Input 
                  className="input"
                  type="text"
                  value={community}
                  onChange={(e)=>setCommunity(e)}
                  placeholder="请填入您居住的小区名称"
                  placeholderClass="placeholder"
                />
              </View>

              <View className="form-item">
                <View className="label">楼栋号</View>
                <Input 
                  className="input"
                  type="text"
                  value={building}
                  onChange={(e)=>setBuilding(e)}
                  placeholder="请填入您的楼栋号码"
                  placeholderClass="placeholder"
                />
              </View>

              <View className="form-item unit-room">
                <View className="unit">
                  <Input 
                    className="input"
                    type="text"
                    value={unit}
                    onChange={(e)=>setUnit(e)}
                    placeholder="单元"
                    placeholderClass="placeholder"
                  />
                </View>
                <View className="separator">-</View>
                <View className="room">
                  <Input 
                    className="input"
                    type="text"
                    value={room}
                    onChange={(e)=>setRoom(e)}
                    placeholder="门牌号"
                    placeholderClass="placeholder"
                  />
                </View>
              </View>

              <View className="tips">
                *您的住址信息仅用于多多帮服务使用，住址变更时可至「我的-居住地址」中更新
              </View>
            </View>
          </View>
        }
        onConfirm={() => {
          // 保存地址
          handleSave();
        }}
      />
    </View>
  );
}
